package ipgather.core.host.thread;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import ipgather.core.proxy.thread.ProxyCheck;
import ipgather.entity.Host;
public class JPortScannerByNIO {

	public static void main(String[] args) throws IOException {
        int port = 80;
        Random random = new Random();
        Selector selector = Selector.open();
        for (int tail = 1; tail < 20000; tail++) {
            SocketChannel channel = SocketChannel.open();
            int ip1 = random.nextInt(200)+1;
            String ip = new StringBuffer(7).append(ip1==127?127-(random.nextInt(40)):ip1).append(".").append(random.nextInt(255)+1).append(".").append(random.nextInt(255)+1).append(".").append(random.nextInt(255)+1).toString();
            SocketAddress address = new InetSocketAddress(ip, port);
            channel.configureBlocking(false);
            channel.connect(address);
            channel.register(selector, SelectionKey.OP_CONNECT, address);// 这里你也可以用输入或者输出
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ProxyCheck proxyCheck = new ProxyCheck(httpClient);
        new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
		        	selector.select(1000);//这里可以设置超时时间
		        } catch (IOException e) {
		        	e.printStackTrace();
		        }
		        Set<SelectionKey> keys = selector.selectedKeys();
		        for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
		        	SelectionKey key = it.next();
		        	it.remove();
		        	String ks = key.attachment().toString().substring(1);
		        	if (key.isConnectable()&&proxyCheck.checkProxyHost(new Host(ks.split(":")[0], Integer.parseInt(ks.split(":")[1])))) {
		        		System.err.println(ks);
		        		key.cancel();
		        	}
		        }
			}
		}).start();
        
    }
}
